<template>
    <div class="chat-container">
      <div class="chat-header">欢迎使用预约AI智能客服</div>
      <div class="chat-messages-container" ref="chatMessages">
        <div v-for="(message, index) in activities" :key="index" 
             :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-content">
            {{ message.content }}
          </div>
          <div class="message-time">{{ message.timestamp }}</div>
        </div>
      </div>
      <div class="chat-input">
        <el-input
          v-model="msg"
          placeholder="请输入您的问题"
          type="text"
          @keyup.enter.native="sendMessage"
        >
          <el-button slot="append" type="primary" @click="sendMessage">发送</el-button>
        </el-input>
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    name: 'AiChat',
    data() {
      return {
        activities: [
          {
            content: '⭐欢迎来到文化馆AI智能客服！请问有什么可以帮您的?',
            timestamp: this.formatTime(new Date()),
            type: 'ai',
          },
        ],
        msg: '',
        loading: false,
        cancelToken: null,
      }
    },
    methods: {
      formatTime(date) {
        return date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
      },
      async sendMessage() {
        if (!this.msg.trim()) return;
  
        if (this.cancelToken) {
          this.cancelToken.cancel('Operation canceled by the user.');
        }
  
        this.cancelToken = axios.CancelToken.source();
  
        this.activities.push({
          content: this.msg,
          timestamp: this.formatTime(new Date()),
          type: 'user',
        });
  
        this.activities.push({
          content: '...',
          timestamp: this.formatTime(new Date()),
          type: 'ai',
        });
  
        const userMessage = this.msg;
        this.msg = '';
        const count = this.activities.length - 1;
  
        try {
          await axios.get(`/ai/generateStreamAsString?message=${encodeURIComponent(userMessage)}`, {
            cancelToken: this.cancelToken.token,
            responseType: 'text',
            onDownloadProgress: (progressEvent) => {
              const xhr = progressEvent.target;
              const { responseText } = xhr;
              
              if (responseText) {
                const chunks = responseText.split('\n')
                  .filter(chunk => chunk.startsWith('data:'))
                  .map(chunk => {
                    try {
                      return chunk.substring(5).trim();
                    } catch (e) {
                      return '';
                    }
                  })
                  .filter(chunk => chunk && chunk !== '[complete]');
                
                const fullMessage = chunks.join('');
                this.activities[count].content = fullMessage;
                
                this.$nextTick(() => {
                  const container = this.$refs.chatMessages;
                  container.scrollTop = container.scrollHeight;
                });
              }
            }
          });
        } catch (error) {
          if (!axios.isCancel(error)) {
            console.error('Error:', error);
            this.activities[count].content = '抱歉，服务出现了问题，请稍后再试。';
          }
        } finally {
          this.cancelToken = null;
        }
      }
    },
    beforeDestroy() {
      if (this.cancelToken) {
        this.cancelToken.cancel('Component unmounted');
      }
    },
  };
  </script>
  
  <style scoped>
  .chat-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .chat-header {
    text-align: center;
    padding: 15px 0;
    font-size: 18px;
    font-weight: bold;
    background-color: #409EFF;
    color: white;
  }
  
  .chat-messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
    background-color: #f5f5f5;
  }
  
  .message {
    max-width: 70%;
    margin-bottom: 15px;
    padding: 10px 15px;
    border-radius: 5px;
    position: relative;
  }
  
  .ai-message {
    align-self: flex-start;
    background-color: white;
    border: 1px solid #eaeaea;
    margin-right: auto;
    border-radius: 0 8px 8px 8px;
  }
  
  .user-message {
    align-self: flex-end;
    background-color: #409EFF;
    color: white;
    margin-left: auto;
    border-radius: 8px 0 8px 8px;
  }
  
  .message-content {
    word-wrap: break-word;
    line-height: 1.5;
  }
  
  .message-time {
    font-size: 11px;
    color: #999;
    margin-top: 5px;
    text-align: right;
  }
  
  .chat-input {
    padding: 15px;
    background-color: white;
    border-top: 1px solid #eee;
    height: 60px;
    display: flex;
    align-items: center;
  }
  
  .el-input {
    flex: 1;
    border-radius: 20px;
    overflow: hidden;
  }
  
  .el-button {
    border-radius: 0 20px 20px 0;
  }
  </style>